<?php

namespace App\Http\Controllers\VideoApi;

use App\Models\video\BroadcasterModel;
use App\Models\video\CommentModel;
use App\Models\video\CommonServer;
use App\Models\video\CourseCatalogModel;
use App\Models\video\CourseModel;
use App\Models\video\CourseViewRecordModel;
use App\Models\video\DataCacheModel;
use App\Models\video\OperateModeModel;
use App\Models\video\OrderModel;
use App\Models\video\PlayedRecordModel;
use App\Models\video\PlayListModel;
use App\Models\video\ReplyModel;
use App\Models\video\SubscriptionModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VideoUserModel;
use App\Models\video\VodHandle;
use App\Models\video\VodVideoModel;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class VideoController extends BaseController
{
    public function __construct(Request $request)
    {
        $this->noCheckTokenAction = ['getVideoInfo', 'getVideoList', 'getRecommendVideo']; //不校验openid
        parent::__construct($request);
    }

    // 首页列表
    public function getVideoList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $filter = ["handle_result" => 2, "status" => 1, "type" => 1];
        $filter1 = ['status' => 1];
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        if($settingData["operateMode"] == '1'){
            $id = BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1]);
            $filter["broadcaster_id"] = $id;
            $filter1["broadcaster_id"] = $id;
        }
        $field = "id,title,cover_img_id,create_time,view_count,video_length,broadcaster_id,type,file_type";
        $data = VodVideoModel::getList($field, $filter, $request->page ?: 1, $request->pageSize ?: 18, "view_count", "desc");
        foreach ($data["list"] as &$item){
            $item["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "type" => 1, "status" => 1, "mall_id" => $request->mallData["id"]]) +
                ReplyModel::query()->from(ReplyModel::query()->getModel()->getTable(). " as r")
                    ->leftJoin(CommentModel::query()->getModel()->getTable()." as c", "c.id", '=', "r.comment_id")
                    ->where(["c.belong_id" => $item["id"], "r.status" => 1])
                    ->count();
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 获取普通视频信息
    public function getVideoInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data = VodVideoModel::getFields("*", ["id" => $request->id]);
        if(!empty($data)){
            if($data["type"] == '2'){ // 课程
                $data = $this->handleCourseVideoData($data, $request);
            }else{ // 视频
                $data = $this->handleVideoData($data, $request);
            }
            if(!empty($data)) {
                foreach ((array)$data["videoUrlList"] as $key => $item) {
                    $data["videoUrlList"][$key]["url"] = VodHandle::getInstance()->getUrlBySign($item["url"], $data["videoDuration"], $data["tryTime"]);
                }
                $data["viewStatus"] = $data["userFreeWatch"] == "1" ? 1 : ($data["tryTime"] ? 2 : 3); // 1 - 免费；2 - 试看；3 - 付费
                $data["mediaUrl"] = VodHandle::getInstance()->getUrlBySign($data["mediaUrl"], $data["videoDuration"], $data["tryTime"]);
                $this->returnData["data"] = $data;
            }else{
                $this->returnData["data"] = [];
            }
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    private function handleCourseVideoData($data, Request $request){
        $courseData = CourseModel::query()->from(CourseModel::query()->getModel()->getTable()." as c")
            ->leftJoin(CourseCatalogModel::query()->getModel()->getTable()." as cc", "c.id", "=", "cc.course_id")
            ->where(["cc.video_id" => $request->id])
            ->select("c.pay_mode", "c.member_mode", "c.id")
            ->first();
        if(!empty($courseData)){
            if($courseData->pay_mode != '0') { // 需付费
                $data["userFreeWatch"] = 0; // 1 - 免费看， 0 - 付费
                if(!$data["tryTime"]) {
                    $data["tryTime"] = VodHandle::getInstance()->getTryTime($data["videoDuration"]); // 试看时长
                }
            }else{
                $data["userFreeWatch"] = 1; // 1 - 免费看，0 - 付费
                $data["tryTime"] = 0;
            }
            if($request->token && $userId = $this->getTokenVar($request->token, "id")){
                if(empty(DataCacheModel::getValue(DataCacheModel::$userWatchMark."_{$request->id}_".$userId))){ // 一个用户只能记录一次观看次数
                    VodVideoModel::doUpdate(["view_count" => DB::raw("view_count+1")], ["id" => $request->id]);
                    DataCacheModel::saveCache(["key" => DataCacheModel::$userWatchMark."_{$request->id}_".$userId, "value" => true]);
                }
                $recordData = CourseViewRecordModel::getFields("id", ["user_id" => $userId, "course_id" => $courseData->id], true, false);
                if (empty($recordData['id'])) { // 记录观看课程
                    CourseViewRecordModel::toAdd(["user_id" => $userId, "course_id" => $courseData->id, "video_id" => $request->id]);
                } else {
                    CourseViewRecordModel::doUpdate(["created_at" => Carbon::now(), "video_id" => $request->id], ["id" => $recordData["id"]]);
                }
                if($courseData->pay_mode != '0'){ // 需付费
                    $data["userFreeWatch"] = 0; // 1 - 免费看， 0 - 付费
                    $orderExist = OrderModel::query()->where(["user_id" => $userId, "mall_id" => $request->mallData["id"], "type" => 2, "belong_id" => $courseData->id])
                        ->whereIn("status", [2,4,5])
                        ->count();
                    if ($orderExist) {
                        $data["tryTime"] = 0;
                        $data["userFreeWatch"] = 1;
                    }else {
                        $settingData = VideoSettingModel::getFields("open_member,member_discount", ["mall_id" => $request->mallData["id"]], true, false);
                        $userData = VideoUserModel::getFields("level_time", ["id" => $userId], true, false);
                        if ($courseData->pay_mode == '1' && $settingData["openMember"] == '1') { // 收费模式  memberMode ：0会员免费，1会员折扣
                            if ($courseData->member_mode == '0' && $userData["levelTime"] > time()) { // 0会员免费
                                $data["userFreeWatch"] = 1;
                                $data["tryTime"] = 0;
                            }
                        } elseif ($courseData->pay_mode == '2' && $userData["levelTime"] > time()) { // 会员免费
                            $data["userFreeWatch"] = 1;
                            $data["tryTime"] = 0;
                        }
                    }
                }
            }
        }else {
            $data = [];
        }
        return $data;
    }

    private function handleVideoData($data, Request $request){
        $data["memberPayMoney"] = 0; // 用户支付价格
        $data["userFreeWatch"] = 1; // 1 - 免费看， 0 - 付费
        $data["subscribe"] = 0; // 未订阅
        $data["praiseStatus"] = 0; // 赞状态
        $data["treadStatus"] = 0; // 踩状态
        $settingData = VideoSettingModel::getFields("open_member,member_discount", ["mall_id" => $request->mallData["id"]], true, false);
        $data["openMember"] = $settingData["openMember"];
        if($data["payMode"] != '0'){
            if(!$data["tryTime"]) {
                $data["tryTime"] = VodHandle::getInstance()->getTryTime($data["videoDuration"]); // 试看时长
            }
            $data["memberPayMoney"] = CommonServer::price_format($data["payMoney"]);
            $data["userFreeWatch"] = 0;
        }
        if($request->token){
            $userId = $this->getTokenVar($request->token, "id");
            if(!$userId){
                return $this->return_result($this->returnData);
            }
            if(empty(DataCacheModel::getValue(DataCacheModel::$userWatchMark."_{$request->id}_".$userId))){ // 一个用户只能记录一次观看次数
                VodVideoModel::doUpdate(["view_count" => DB::raw("view_count+1")], ["id" => $request->id]);
                DataCacheModel::saveCache(["key" => DataCacheModel::$userWatchMark."_{$request->id}_".$userId, "value" => true]);
            }
            $recordData = PlayedRecordModel::getFields("id", ["user_id" => $userId, "video_id" => $request->id], true, false);
            if(empty($recordData)){
                PlayedRecordModel::toAdd(["user_id" => $userId, "video_id" => $request->id, "broadcaster_id" => $data["broadcasterId"]]);
            }else{
                PlayedRecordModel::doUpdate(["create_time" => time()], ["id" => $recordData["id"]]);
            }
            $tempData = SubscriptionModel::getFields("remind_status", ["broadcaster_id" => $data["broadcasterId"], "user_id" => $request->userLoginData["id"]]);
            if (!empty($tempData)) {
                $data["subscribe"] = 1; // 已订阅
            }
            $data["likeStatus"] = PlayListModel::query()->where(["class_id" => -1, "user_id" => $request->userLoginData["id"], "video_id" => $data["id"]])->count(); // 收藏状态
            if($data["payMode"] != '0'){ // 需付费
                $orderExist = OrderModel::query()->where(["user_id" => $userId, "mall_id" => $request->mallData["id"], "type" => 1, "belong_id" => $data["id"]])
                    ->whereIn("status", [2,4,5])
                    ->count();
                if ($orderExist) {
                    $data["tryTime"] = 0;
                    $data["memberPayMoney"] = CommonServer::price_format(0);
                    $data["userFreeWatch"] = 1;
                }else {
                    $userData = VideoUserModel::getFields("level_time", ["id" => $userId], true, false);
                    if ($data["payMode"] == '1' && $settingData["openMember"] == '1') { // 收费模式  memberMode ：0会员免费，1会员折扣
                        if ($data["memberMode"] == '0') { // 0会员免费
                            if ($userData["levelTime"] > time()) {
                                $data["userFreeWatch"] = 1;
                                $data["tryTime"] = 0;
                            }
                            $data["memberPayMoney"] = CommonServer::price_format(0);
                        } elseif (!empty($settingData["memberDiscount"])) { // 折扣价
                            $data["memberPayMoney"] = CommonServer::price_format($data["memberPayMoney"] * $settingData["memberDiscount"] / 100);
                        }
                    } elseif ($data["payMode"] == '2') { // 会员免费
                        if ($userData["levelTime"] > time()) {
                            $data["userFreeWatch"] = 1;
                            $data["tryTime"] = 0;
                        }
                        if ($settingData["openMember"] == '1') {
                            $data["memberPayMoney"] = CommonServer::price_format(0);
                        }
                    }
                }
            }
            $data["praiseStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $data["id"], "type" => 4, "mode" => 1]);
            $data["treadStatus"] = OperateModeModel::getCount(["user_id" => $userId, "belong_id" => $data["id"], "type" => 4, "mode" => 2]);
        }
        $data["commentCount"] = CommentModel::getCount(["belong_id" => $data["id"], "type" => 1, "status" => 1, "mall_id" => $request->mallData["id"]]) +
            ReplyModel::query()->from(ReplyModel::query()->getModel()->getTable(). " as r")
                ->leftJoin(CommentModel::query()->getModel()->getTable()." as c", "c.id", '=', "r.comment_id")
                ->where(["c.belong_id" => $data["id"], "r.status" => 1])
                ->count();
        $data["likeCount"] = PlayListModel::getCount(["class_id" => -1, 'mall_id' => $request->mallData["id"], "video_id" => $data["id"]]); // 收藏次数
        $data["barrageCount"] = 0; // 弹幕数
        $data["praiseCount"] = OperateModeModel::getCount(["belong_id" => $data["id"], "type" => 4, "mode" => 1]); // 点赞数
        $data["fanNumber"] = BroadcasterModel::getValue("fan_number", ["id" => $data["broadcasterId"]]); // 粉丝数
        return $data;
    }

    public function getRecommendVideo(Request $request){ // 分区，标题，作者
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $settingData = VideoSettingModel::getFields("operate_mode", ["mall_id" => $request->mallData["id"]]);
        $filter = ["handle_result" => 2, "status" => 1, "type" => 1];
        if($settingData["operateMode"] == '1'){
            $filter["broadcaster_id"] = BroadcasterModel::getValue("id", ["mall_id" => $request->mallData["id"], "status" => 1]);
        }
        if($request->videoId){
            $temp = VodVideoModel::getFields("broadcaster_id,title,cat_id", ["id" => $request->videoId], true, false);
            $db = VodVideoModel::query()->select("id","title","desc","cover_img_id","create_time","view_count","video_length","broadcaster_id", "file_type")
                ->where($filter)
                ->orWhere("broadcaster_id", $temp["broadcasterId"])//->orWhere("title", "like", "%".mb_substr($temp["title"], 0, 1)."%")
                ->orWhere("cat_id", $temp["catId"]);
        }else{
            $db = VodVideoModel::query()->where($filter)->select("id","title","desc","cover_img_id","create_time","view_count","video_length","broadcaster_id", "file_type");
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 20;
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("create_time", "desc")->get()->toArray();
        $data['list'] = VodVideoModel::transferField($data['list']);
        foreach ($data["list"] as &$item){
            $item["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "status" => 1, "type" => 1]); // 评论次数
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }
}
